package com.design.graduation.asdemo.manager;

import com.design.graduation.asdemo.network.model.TokenResult;
import com.design.graduation.asdemo.network.service.HttpObserver;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import java.io.File;

import rx.Observable;
import rx.Observer;

/**
 * Created by locfai on 2016/4/8.
 */
public class QiniuManager {
    private static UploadManager uploadManager = new UploadManager();

    private static void putFile(byte[] data, String fileKey, String token, UpCompletionHandler
            upCompletionHandler) {
        uploadManager.put(data, fileKey, token, upCompletionHandler, null);
    }

    private static void putFile(File file, String fileKey, String token, UpCompletionHandler
            upCompletionHandler) {
        uploadManager.put(file, fileKey, token, upCompletionHandler, null);
    }

    /**
     * 上传字节数组的文件，若要指定文件名，则传fileKey，否则fileKey为null
     *
     * @param byteData            文件字节数组
     * @param fileKey             文件名
     * @param upCompletionHandler 上传完成回调
     */
    public static void uploadFile(String id,final byte[] byteData, final String fileKey, final
    UpCompletionHandler upCompletionHandler) {
        UserManager.getToken(id,new HttpObserver<TokenResult>() {
            @Override
            public void onSuccess(TokenResult tokenResult) {
                putFile(byteData, fileKey, tokenResult.getToken(), upCompletionHandler);
            }

            @Override
            public void onNetworkError() {

            }
        });
    }


    public static Observable<String> uploadFile(final File file, String upLoadToken, final String
            fileKey, final UpCompletionHandler upCompletionHandler) {
        putFile(file, fileKey, upLoadToken, upCompletionHandler);
        return Observable.just(upLoadToken);
    }

    /**
     * 上传文件到七牛，若要指定文件名称，则传fileKey，否则fileKey为null
     *
     * @param file                要上传的文件
     * @param fileKey             文件名称
     * @param upCompletionHandler 上传完成回调
     */
    public static void uploadFile(String id, final File file, final String fileKey, final
    UpCompletionHandler upCompletionHandler) {

        UserManager.getToken(id, new Observer<TokenResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(TokenResult tokenResult) {
                putFile(file, fileKey, tokenResult.getToken(), upCompletionHandler);
            }
        });
    }
}
